package com.ssyt.ec.common.util;

import java.security.MessageDigest;

/**
 * MD5加密串生成算法
 * 
 * @author Hsu。
 * @since 2015-1-17
 */
public class MD5Util {

	/**
	 * 主方法测试
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		String s = new String("admin");

		System.out.println(MD5Util.toMD5(s));

		System.out.println("原始：" + s);
		System.out.println("MD5加密后：" + md5(s));
		System.out.println("MD5后再加密：" + reverse(md5(s)));
		System.out.println("解密为MD5后的：" + encrypt(reverse(md5(s))));
		System.out.println("加密的：" + reverse(s));
		System.out.println("解密的：" + encrypt(reverse(s)));
	}

	/**
	 * MD5加密。32位 .
	 * 
	 * @param oldPassword
	 *            未加密的原文密码
	 * @return the string
	 */
	public static String md5(String oldPassword) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		char[] charArray = oldPassword.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++) {
			byteArray[i] = (byte) charArray[i];
		}

		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();

		for (byte md5Byte : md5Bytes) {
			int val = md5Byte & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}

		return hexValue.toString();
	}

	/**
	 * 加密后解密(即：将二次加密密码解密为 MD5格式).
	 * 
	 * @param inStr
	 *            the in str
	 * @return the string
	 */
	public static String encrypt(String inStr) {
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String k = new String(a);
		return k;
	}

	/**
	 * 可逆的加密算法（即：对MD5再进行加密）.
	 * 
	 * @param inStr
	 *            the in str
	 * @return the string
	 */
	public static String reverse(String inStr) {
		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;
	}

	/**
	 * hexDigits[],可自定义转16进制的规则
	 * 
	 * @param s
	 * @return
	 */
	public final static String toMD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			// byte[]转为16进制字符串的原生写法：会补足两位自动在前面加0
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

}
